// API配置
const API_BASE_URL = (() => {
    const currentHost = window.location.hostname;
    
    // 如果是内网穿透域名，使用相对路径
    if (currentHost.includes('oicp.vip') || currentHost.includes('ngrok') || currentHost.includes('tunnel')) {
        return '/api';
    }
    
    // 本地开发环境
    return 'http://localhost:3001/api';
})();

// 查询进度功能
async function queryProgress() {
    const clueNo = document.getElementById('clueNo').value.trim();
    const phone = document.getElementById('queryPhone').value.trim();
    
    if (!clueNo) {
        showAlert('请输入举报编号', 'warning');
        return;
    }
    
    try {
        showAlert('正在查询...', 'info');
        
        let endpoint = `/clues/${clueNo}/status`;
        if (phone) {
            endpoint += `?phone=${encodeURIComponent(phone)}`;
        }
        
        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        });
        
        const result = await response.json();
        
        if (result.code === 200) {
            showQueryResult(result.data);
        } else {
            showAlert(result.message || '查询失败', 'danger');
        }
    } catch (error) {
        console.error('查询失败:', error);
        showAlert('查询失败：网络连接错误', 'danger');
    }
}

// 显示查询结果
function showQueryResult(data) {
    const modal = document.getElementById('queryModal');
    const modalBody = modal.querySelector('.modal-body');
    
    const statusMap = {
        'pending': { text: '待处理', class: 'warning' },
        'processing': { text: '处理中', class: 'info' },
        'completed': { text: '已完成', class: 'success' },
        'rejected': { text: '已驳回', class: 'danger' }
    };
    
    const status = statusMap[data.status] || { text: '未知状态', class: 'secondary' };
    
    modalBody.innerHTML = `
        <div class="alert alert-${status.class}">
            <h5><i class="fas fa-info-circle me-2"></i>查询结果</h5>
            <hr>
            <div class="row">
                <div class="col-sm-4"><strong>举报编号：</strong></div>
                <div class="col-sm-8">${data.clue_no}</div>
            </div>
            <div class="row mt-2">
                <div class="col-sm-4"><strong>当前状态：</strong></div>
                <div class="col-sm-8">
                    <span class="badge bg-${status.class}">${status.text}</span>
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-sm-4"><strong>提交时间：</strong></div>
                <div class="col-sm-8">${new Date(data.created_at).toLocaleString()}</div>
            </div>
            ${data.updated_at ? `
            <div class="row mt-2">
                <div class="col-sm-4"><strong>更新时间：</strong></div>
                <div class="col-sm-8">${new Date(data.updated_at).toLocaleString()}</div>
            </div>
            ` : ''}
            ${data.remark ? `
            <div class="row mt-2">
                <div class="col-sm-4"><strong>处理备注：</strong></div>
                <div class="col-sm-8">${data.remark}</div>
            </div>
            ` : ''}
        </div>
        <div class="text-center">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            <button type="button" class="btn btn-primary" onclick="resetQueryForm()">继续查询</button>
        </div>
    `;
}

// 重置查询表单
function resetQueryForm() {
    document.getElementById('clueNo').value = '';
    document.getElementById('queryPhone').value = '';
    
    const modal = document.getElementById('queryModal');
    const modalBody = modal.querySelector('.modal-body');
    
    modalBody.innerHTML = `
        <form id="queryForm">
            <div class="mb-3">
                <label for="clueNo" class="form-label">举报编号</label>
                <input type="text" class="form-control" id="clueNo" placeholder="请输入您的举报编号" required>
                <div class="form-text">举报编号在提交成功后获得</div>
            </div>
            <div class="mb-3">
                <label for="queryPhone" class="form-label">联系电话（可选）</label>
                <input type="tel" class="form-control" id="queryPhone" placeholder="请输入举报时填写的电话号码">
                <div class="form-text">用于验证身份，提高查询准确性</div>
            </div>
        </form>
    `;
    
    // 重新绑定查询按钮
    const queryBtn = modal.querySelector('.modal-footer .btn-primary');
    queryBtn.onclick = queryProgress;
    queryBtn.innerHTML = '<i class="fas fa-search me-2"></i>查询';
}

// 显示提示信息
function showAlert(message, type = 'info') {
    // 移除现有的提示
    const existingAlert = document.querySelector('.alert-floating');
    if (existingAlert) {
        existingAlert.remove();
    }
    
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show alert-floating`;
    alertDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    `;
    
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.classList.remove('show');
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 150);
        }
    }, 3000);
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('🏠 主页加载完成');
    
    // 绑定查询表单提交事件
    const queryForm = document.getElementById('queryForm');
    if (queryForm) {
        queryForm.addEventListener('submit', function(e) {
            e.preventDefault();
            queryProgress();
        });
    }
    
    // 添加平滑滚动效果
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
    
    // 添加滚动动画效果
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);
    
    // 观察需要动画的元素
    document.querySelectorAll('.feature-card, .card').forEach(el => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';
        el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(el);
    });
});

// 全局函数，供HTML调用
window.queryProgress = queryProgress;
window.resetQueryForm = resetQueryForm; 